import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Dropdown, Menu, Icon, Checkbox } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import DataForm from './components/DataForm';
import QR from './components/QR';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';
import { useHistory } from 'react-router';
import styles from './index.module.scss';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';

const tableId = uniqueId('tauTable-');

function CompanyInfo() {
  const [modal, setModal] = useState([]);
  const [QRModal, setQRModal] = useState({});
  const { companyStore: store } = useStore();
  const companyRef = useRef();
  const [showOrders, setShowOrders] = useState(false);
  const [showVehicle, setShowVehicle] = useState(false);
  const [showDriver, setShowDriver] = useState(false);
  const [extras, setExtras] = useState({
    vehicle: [],
    driver: [],
    ccOrders: [],
    scOrders: [],
  });
  const history = useHistory();

  useEffect(() => {
    (async () => {
      await store.getPayMerchant();
    })();
  }, []);

  // 监听订单
  useEffect(() => {
    if (showOrders) {
      (async () => {
        const ccOrders = await fetchCcOrderCounts();
        const scOrders = await fetchScOrderCounts();
        setExtras({
          ...extras,
          ccOrders,
          scOrders,
        });
      })();
    } else {
      setExtras({
        ...extras,
        ccOrders: [],
        scOrders: [],
      });
    }
  }, [showOrders, store.company]);

  // 监听司机
  useEffect(() => {
    if (showDriver) {
      (async () => {
        const driver = await fetchDriverCounts();
        setExtras({
          ...extras,
          driver,
        });
      })();
    } else {
      setExtras({
        ...extras,
        driver: [],
      });
    }
  }, [showDriver, store.company]);

  // 监听车辆
  useEffect(() => {
    if (showVehicle) {
      (async () => {
        const vehicle = await fetchVehicleCounts();
        setExtras({
          ...extras,
          vehicle,
        });
      })();
    } else {
      setExtras({
        ...extras,
        vehicle: [],
      });
    }
  }, [showVehicle, store.company]);

  async function fetchCcOrderCounts() {
    const promiseAry = store.company.map((p) => store.api.ccOrderCount({
      search: {
        companyId: p.id,
      },
    }).then((r) => ({ id: p.id, count: r })));
    return Promise.all(promiseAry);
  }

  async function fetchScOrderCounts() {
    const promiseAry = store.company.map((p) => store.api.scOrderCount({
      search: {
        companyId: p.id,
      },
    }).then((r) => ({ id: p.id, count: r })));
    return Promise.all(promiseAry);
  }

  async function fetchVehicleCounts() {
    const promiseAry = store.company.map((p) => store.api.vehiclesCount({
      search: {
        companyId: p.id,
      },
    }).then((r) => ({ id: p.id, count: r })));
    return Promise.all(promiseAry);
  }

  async function fetchDriverCounts() {
    const promiseAry = store.company.map((p) => store.api.driversCount({
      search: {
        companyId: p.id,
      },
    }).then((r) => ({ id: p.id, count: r })));
    return Promise.all(promiseAry);
  }

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { registerAddr, status, getOnDate, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      registerAddr,
      status,
      from,
      to,
      ...searchArgs,
    };
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    companyRef.current = {};
    setModal(['add']);
  };

  // 点击打开查看
  const handleOpenView = (company) => {
    companyRef.current = company;
    setModal(['view']);
  };

  // 点击打开编辑
  const handleOpenEdit = (company) => {
    companyRef.current = company;
    setModal(['edit']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 打开二维码
  const handelOpenQR = async (company) => {
    try {
      const { name, id } = company;
      setQRModal({
        open: true,
        name,
        onCancel: QROnCancel,
        okText: '下载',
        id,
      });
    } catch (error) {
      console.log('🚀 _ file: index.jsx:183 _ error:', error);
    }
  };

  // 关闭二维码
  const QROnCancel = () => {
    setQRModal({ open: false });
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        Message.success({ content: t`承运商创建成功` });
      } catch (e) {
        Message.error({ content: t`承运商创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 查看车辆
  const handleOpenVehicle = (r) => {
    companyRef.current = r;
    setModal(['vehicle']);
  };

  // 查看司机
  const handleOpenDriver = (r) => {
    companyRef.current = r;
    setModal(['driver']);
  };

  // 查看包车订单
  const handleOpenCCOrder = (r) => {
    companyRef.current = r;
    setModal(['ccOrder']);
  };

  // 查看包车订单
  const handleOpenSCOrder = (r) => {
    companyRef.current = r;
    setModal(['scOrder']);
  };

  // 跳转承运商
  const handleRoute = (company) => {
    const { id } = company;
    return history.push(`/company/info/${id}/route`);
  };

  // 跳转承运商
  const handleRouteSetting = (company) => {
    const { id, name } = company;
    store.companyName = name;
    return history.push(`/company/info/${id}/setting`);
  };

  const handleCustomRequest = ({ file, onSuccess, onError }) => {
    const reader = new FileReader();
    reader.onloadend = async () => {
      try {
        await RSocket.rc({
          route: 'files.upload',
          args: {
            binary: {
              binaryId: companyRef.current?.id,
              mimeType: file.type,
              filename: file.name,
            },
          },
          data: Buffer.from(reader.result),
        });
        onSuccess();
      } catch (e) {
        onError(e);
        Message.warning('上传失败');
      } finally {
        // eslint-disable-next-line no-undef
      }
    };
    reader.readAsArrayBuffer(file);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-placeChannel',
            title: t`添加承运商`,
            type: 'primary',
            onClick: handleOpenAdd,
          },
        ]}
        searchItems={[
          {
            name: 'registerAddr',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.cityName),
              placeholder: t`注册地区`,
            },
          },
          {
            name: 'status',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.statusName),
              placeholder: t`启用状态`,
            },
          },
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`起始更新时间`, t`结束更新时间`],
            },
          },
        ]}
        extraItems={[
          {
            name: 'cbx-showDriver',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowVehicle(v)}>{t`查看车辆`}</Checkbox>,
          },
          {
            name: 'cbx-showVehicle',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowDriver(v)}>{t`查看司机`}</Checkbox>,
          },
          {
            name: 'cbx-showOrders',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowOrders(v)}>{t`查看订单`}</Checkbox>,
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.company)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', { width: 78, cell: (v, _, company) => <Button type="primary" text onClick={() => handleOpenView(company)}>{v}</Button> }),
            column('name', { width: 88 }),
            column('registerAddr', { width: 58 }),
            column('vehicleNum', { width: 88, cell: (v, _, company) => <Button type="primary" text onClick={() => handleOpenVehicle(company)}>{extras.vehicle.find((n) => n?.id === company?.id)?.count || 0}</Button> }),
            column('driverNum', { width: 88, cell: (v, _, company) => <Button type="primary" text onClick={() => handleOpenDriver(company)}>{extras.driver.find((n) => n?.id === company?.id)?.count || 0}</Button> }),
            column('status', { width: 88 }),
            column('ccOrderNum', { width: 88, cell: (v, _, company) => <Button type="primary" text onClick={() => handleOpenCCOrder(company)}>{extras.ccOrders.find((n) => n?.id === company?.id)?.count || 0}</Button> }),
            column('scOrderNum', { width: 88, cell: (v, _, company) => <Button type="primary" text onClick={() => handleOpenSCOrder(company)}>{extras.scOrders.find((n) => n?.id === company?.id)?.count || 0}</Button> }),
            column('upDate', { width: 98 }),
            {
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 200,
              cell: (_, __, company) => {
                return (
                  <>
                    <Button text type="primary" onClick={() => handleOpenEdit(company)} >{t`编辑`}</Button>
                    <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                    <Button text type="primary" onClick={() => handleRoute(company)}>{t`承运线路`}</Button>
                    <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                    <Dropdown trigger={<a style={{ color: '#5584FF' }} className={styles.dropdown}>更多 <Icon type="arrow-down" size="xs" /></a>} triggerType="click">
                      <Menu>
                        <Menu.Item><Button text type="primary" onClick={() => handleRouteSetting(company)}>{t`设置承运附加费`}</Button></Menu.Item>
                        <Menu.Item><Button text type="primary" onClick={() => handelOpenQR(company)} >{t`二维码`}</Button></Menu.Item>
                      </Menu>
                    </Dropdown>
                  </>
                );
              },
            },
          ]
            .filter((c) => (c.dataIndex !== 'ccOrderNum' || showOrders) && (c.dataIndex !== 'scOrderNum' || showOrders))
            .filter((c) => c.dataIndex !== 'vehicleNum' || showVehicle)
            .filter((c) => c.dataIndex !== 'driverNum' || showDriver)}
        />
      </div>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'edit' || modal[0] === 'view'}
        // eslint-disable-next-line no-nested-ternary
        title={modal[0] === 'add' ? t`添加承运商` : (modal[0] === 'edit' ? t`修改承运商 【${companyRef.current?.name}】` : t`查看承运商 【${companyRef.current?.name}】`)}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <DataForm
          companyId={companyRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
          handleCustomRequest={handleCustomRequest}
        />
      </Drawer>
      <QR modal={QRModal} />
      <ComponentsDrawer modal={modal} queryParams={{ companyId: companyRef.current?.id }} name={companyRef.current?.name} onCancel={handleCancel} />
    </TauPage>
  );
}

export default observer(CompanyInfo);
